<template>
  <div>
    <el-form ref="formRef" v-loading="formLoading" :model="userInfo" :rules="formRules" :label-width="100"
      style="max-width: 300px;margin-top: 2%;">
      <el-form-item label="用户头像" prop="avatarUrl">
        <!-- <div class="text-center">
          <UserAvatar :img="userInfo?.avatarUrl" @avatar="getAvatar" />
        </div> -->
        <UploadImg v-model="userInfo.avatarUrl" :limit="1" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="userInfo.nickName" placeholder="请输入用户昵称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUserInfo">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import UserAvatar from './UserAvatar.vue'
import * as ProfileApi from '@/api/system/user/profile'
import { useUserStore } from '@/store/modules/user'
import { getUserId } from '@/utils/auth'
const userStore = useUserStore()
const message = useMessage() // 消息弹窗


defineOptions({ name: 'ProfileUser' })

const userInfo = ref({
  avatarUrl: '',
  nickName: ''
})
const formRules = reactive({
  avatarUrl: [{ required: true, message: '用户头像不能为空', trigger: 'blur' }],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用

const getUserInfo = async () => {
  formLoading.value = true
  try {
    const users = await ProfileApi.getuserInfo()
    userInfo.value = users
  } finally {
    formLoading.value = false
  }
}
const submitUserInfo = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    await ProfileApi.savePersonalUserInfo(userInfo.value)
    userStore.setUserAvatarAction(userInfo.value.avatarUrl)
    userStore.setUserNicknameAction(userInfo.value.nickName)
    message.success('保存成功')
    ProfileApi.updateUser({ nickname: userInfo.value.nickName, id: getUserId() })
  } finally {
    formLoading.value = false
  }
}

const getAvatar = (data) => {
  userInfo.value.avatarUrl = data
}

onMounted(async () => {
  await getUserInfo()
})
</script>

<style scoped>
.text-center {
  position: relative;
  height: 120px;
  text-align: center;
}

.list-group-striped>.list-group-item {
  padding-right: 0;
  padding-left: 0;
  border-right: 0;
  border-left: 0;
  border-radius: 0;
}

.list-group {
  padding-left: 0;
  list-style: none;
}

.list-group-item {
  padding: 11px 0;
  margin-bottom: -1px;
  font-size: 13px;
  border-top: 1px solid #e7eaec;
  border-bottom: 1px solid #e7eaec;
}

.pull-right {
  float: right !important;
}
</style>
